package cn.etgps.etgps.blmanager;

import android.content.Context;

import com.alibaba.fastjson.JSON;

import java.util.List;

import cn.etgps.etgps.dataEntity.Model;
import cn.etgps.etgps.dataEntity.TrackReplayBean;
import cn.etgps.etgps.dataEntity.TrackReplayEntity;
import cn.etgps.etgps.dataEntity.TruckBean;
import cn.etgps.etgps.dataEntity.TruckBeanEntity;
import cn.etgps.etgps.dataEntity.TruckDetailEntity;
import cn.etgps.etgps.manager.NetworkManager;
import cn.etgps.etgps.utils.AppUtils;
import cn.etgps.etgps.utils.Constant;

/**
 * 卡车的管理类
 *
 * @author nicky.han
 */
public class TruckManager extends BaseBLManager {
    /*static int count = 0;
    String countSs = "";
    String countSss = "";
    static int di = 0;*/

    public TruckManager(Context context) {
        super(context);
    }

    /**
     * 获取卡车数据从服务器
     *
     * @param list      用来接收卡车数据的列表
     * @param pageCount 当前需要获取的是第几页
     * @return 获取成果，成功/失败/无法连接服务器
     */
    public synchronized String getTrucksFromServer(List<Model> list, int pageCount) {
        String result = NetworkManager.getDataFromServer(
                addUserInfoToURL(Constant.URI_GET_TRUCK_IN_GARAGE) + Constant.PAGE_SIZE_KEY
                        + Constant.PER_PAGE_ITEM_COUNT +
                        Constant.PAGE_INDEX_KEY + pageCount);
        if (result.equals(Constant.CONNECT_TO_SERVER_FAILED)) {
            return Constant.CONNECT_TO_SERVER_FAILED;
        } else {
            TruckBeanEntity entity = JSON.parseObject(result, TruckBeanEntity.class);
            if (entity.getStatus().equals(Constant.RETURN_RESULT_OK) && entity != null) {
                list.addAll(entity.getContent());
             /*   for (int i = 0; i < list.size(); i++) {
                    count++;

                    TruckBean truckStatusBean = (TruckBean) list.get(i);
                    String ss = truckStatusBean.getLicense() + "\n";
                    ss.trim();
                    countSs = ss + countSs;
                    String d = truckStatusBean.getTotalDistance() + "\n";
                    d.trim();
                    countSss = d + countSss;
                    if (!TextUtils.isEmpty(truckStatusBean.getTotalDistance())) {
                        di = Integer.valueOf(truckStatusBean.getTotalDistance()) + di;
                    }
                }*/
              /*  Log.d("hcb", countSs + "共计：" + count + "辆 共" + di + "km");
                Log.d("hcb", countSss + "共计：" + count + "辆 共" + di + "km");
                countSs = "";
                countSss = "";*/
                return "";
            } else {
                return entity.getErrorMsg();
            }
        }
    }

    /**
     * 获取本地缓存的卡车数据
     *
     * @return 数据列表
     */
    public synchronized List<Model> getTrucksFromLocalDB() {
        List<Model> trucks = getDBManager().queryForAll(TruckBean.class.getName());
        return trucks;
    }

    /**
     * 存储卡车数据到本地数据库
     *
     * @param models 卡车数据，本地只缓存第一页的数据
     */
    public synchronized void saveTrucksToLocalDB(List<Model> models) {
        getDBManager().clearTable(TruckBean.class.getName());
        getDBManager().addModels(models);
    }

    /**
     * 根据牌照搜索卡车
     *
     * @param list      用来接收卡车数据
     * @param keyword   搜索关键字
     * @param pageCount 当前需要获取的是第几页
     * @return 获取成果，成功/失败/无法连接服务器
     */
    public synchronized String searchTruckFromServer(List<Model> list, String keyword, int pageCount) {
        String str = addUserInfoToURL(Constant.URI_GET_TRUCK_IN_GARAGE) + "&filter=" + AppUtils.doURLEncode(keyword)
                + Constant.PAGE_SIZE_KEY + Constant.PER_PAGE_ITEM_COUNT +
                Constant.PAGE_INDEX_KEY + AppUtils.doURLEncode(pageCount + "");
        String result = NetworkManager.getDataFromServer(str);
        if (result.equals(Constant.CONNECT_TO_SERVER_FAILED)) {
            return Constant.CONNECT_TO_SERVER_FAILED;
        } else {
            TruckBeanEntity entity = JSON.parseObject(result, TruckBeanEntity.class);
            if (entity.getStatus().equals(Constant.RETURN_RESULT_OK) && entity != null) {
                list.addAll(entity.getContent());
                return "";
            } else {
                return entity.getErrorMsg();
            }
        }
    }

    /**
     * 用来构造需要添加用户信息的URL
     *
     * @param str 原本URL
     * @return 添加用户信息后的url
     */
    private String addUserInfoToURL(String str) {
        String ss = str + Constant.USER_ID_KEY + AppUtils.doURLEncode(getUserID()) + Constant.UER_TYPE_KEY
                + AppUtils.doURLEncode(getUserType());
        return ss;
    }

    /**
     * 从服务器获得卡车详细信息
     *
     * @param vid 卡车的vid
     * @return 卡车信息以及获取结果
     */
    public synchronized TruckDetailEntity detailTruckFromServer(String vid) {
        String result = NetworkManager.getDataFromServer(
                Constant.URL_GET_TRUCK_SEARCH_DETAIL + Constant.SEARCH_VID_KEY + AppUtils.doURLEncode(vid));
        TruckDetailEntity entity = new TruckDetailEntity();
        if (result.equals(Constant.CONNECT_TO_SERVER_FAILED)) {
            entity.setErrorMsg(Constant.CONNECT_TO_SERVER_FAILED);
            return entity;
        } else {
            entity = JSON.parseObject(result, TruckDetailEntity.class);
            if (entity != null) {
                return entity;
            } else {
                entity.setErrorMsg(Constant.JSON_DETE_ERROR);
                return entity;
            }
        }
    }

    /**
     * 获取卡车的历史轨迹数据
     *
     * @param lonlas 轨迹经纬度列表
     * @param time   历史轨迹的时段
     * @return 获取成果，成功/失败/无法连接服务器
     */
    public synchronized String trackReplayFromServer(List<TrackReplayBean> lonlas, String[] time) {
        String result = NetworkManager.getDataFromServer(trackReplayPath(time));
        if (result.equals(Constant.CONNECT_TO_SERVER_FAILED)) {
            return Constant.CONNECT_TO_SERVER_FAILED;
        } else {
            TrackReplayEntity entity = JSON.parseObject(result, TrackReplayEntity.class);
            if (entity != null) {
                if (entity.getStatus().equals(Constant.RETURN_RESULT_OK)) {
                    lonlas.addAll(entity.getContent());
                    return Constant.RETURN_RESULT_OK;
                } else {
                    return entity.getErrorMsg();
                }
            } else {
                return Constant.CONNECT_TO_SERVER_FAILED;
            }
        }
    }

    /**
     * 构造获取轨迹的URL
     *
     * @param time 起始时间和结束时间
     * @return 返回构造后的URL
     */
    private String trackReplayPath(String[] time) {
        return Constant.URL_GET_TRUCK_PLAY_BACK + Constant.PALY_BACK_VEHICLE_ID_KEY + AppUtils.doURLEncode(time[0])
                + Constant.PALY_BACK_START_TIME_KEY + AppUtils.doURLEncode(time[1]) + Constant.PALY_BACK_END_TIME_KEY
                + AppUtils.doURLEncode(time[2]);
    }
}